package iscript.gameFramework.GameLite.content
{
	import com.greensock.events.LoaderEvent;
	import com.greensock.loading.core.LoaderCore;
	import com.greensock.loading.data.DataLoaderVars;
	import com.greensock.loading.data.LoaderMaxVars;
	import com.greensock.loading.DataLoader;
	import com.greensock.loading.LoaderMax;
	import com.greensock.loading.LoaderStatus;
	import flash.utils.Dictionary;
	import iscript.gameFramework.GameLite.events.GameContentEvent;
	
	internal class DataLoaderContent implements IGameContent
	{
		
		private var _data:Dictionary = new Dictionary();
		private var _loaderMax:LoaderMax;
		private var _gameContent:GameContent;
		
		public function DataLoaderContent(gameContent:GameContent)
		{
			_gameContent = gameContent
			var loadvars:LoaderMaxVars = new LoaderMaxVars();
			loadvars.autoLoad(true);
			loadvars.maxConnections(3);
			loadvars.onChildComplete(_onChildCompleteLogic)
			_loaderMax = new LoaderMax(loadvars);
			_loaderMax.load();
		}
		
		private function _onChildCompleteLogic(e:LoaderEvent):void
		{
			_dispatch(DataLoader(e.target));
		}
		
		private function _dispatch(load:DataLoader):void
		{
			var dataload:DataLoader = load;
			var event:GameContentEvent = new GameContentEvent(GameContentEvent.ONLOADXML);
			event.content = dataload;
			event.key = dataload.vars[GameContent.GamneContentKey];
			_gameContent.dispatchEvent(event);
			
			var ev:GameContentEvent = new GameContentEvent(GameContentEvent.EVERYTHING)
			ev.key = dataload.vars[GameContent.GamneContentKey];
			ev.content = dataload;
			_gameContent.dispatchEvent(ev);
		}
		
		//public function get KEY():Array{return _dataload.getAllKeys()}	
		/**
		 * often time key==url   经常碰到把URL作为KEY，所以用的时候key和url经常是一个值.
		 * @param	key
		 * @param	url
		 * @param	param
		 */
		public function add(urlOrRequest:*, key:*, param:DataLoaderVars = null):void
		{
			if (_data[key] == null)
			{
				if (param == null)
					param = new DataLoaderVars();
				param.vars[GameContent.GamneContentKey] = key;
				var dataload:DataLoader = new DataLoader(urlOrRequest, param);
				_data[key] = dataload;
				_loaderMax.append(dataload);
			}
		}
		
		public function addDataLoader(key:*, dataloader:DataLoader):void
		{
			if (dataloader.status == LoaderStatus.COMPLETED)
			{
				if (_data[key] == null)
				{
					_data[key] = dataloader;
					_dispatch(dataloader);
				}
			}
		}
		
		public function get(key:*):DataLoader
		{
			return _data[key];
		}
		
		public function contain(key:*):Boolean
		{
			return _data[key] != null;
		}
		
		public function remove(key:*):void
		{
			if (_data[key] != null)
			{
				LoaderCore(_data[key]).unload();
				LoaderCore(_data[key]).dispose();
				delete _data[key];
			}
		}
	
  }
}